﻿//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Logging Application Block
//===============================================================================

using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Manageability;

namespace EntLibContrib.Logging.Database.Configuration.Manageability
{
	/// <summary>
	/// Represents a mapper for <see cref="ExtendedDatabaseTraceListenerData"/> configuration to Wmi.
	/// </summary>
	public static class ExtendedDatabaseTraceListenerDataWmiMapper
	{
		/// <summary>
		/// Creates the <see cref="ExtendedDatabaseTraceListenerSetting"/> instances that describe the 
		/// configurationObject.
		/// </summary>
		/// <param name="configurationObject">The configuration object for instances that must be managed.</param>
		/// <param name="wmiSettings">A collection to where the generated WMI objects are to be added.</param>
		public static void GenerateWmiObjects(ExtendedDatabaseTraceListenerData configurationObject,
			ICollection<ConfigurationSetting> wmiSettings)
		{
			wmiSettings.Add(
				new ExtendedDatabaseTraceListenerSetting(configurationObject,
					configurationObject.Name,
					configurationObject.DatabaseInstanceName,
					configurationObject.WriteLogSqlCommand,
					configurationObject.AddCategorySqlCommand,
					configurationObject.CommandType,
					configurationObject.Formatter,
					configurationObject.TraceOutputOptions.ToString(),
					configurationObject.Filter.ToString()));
		}

		internal static void RegisterWmiTypes()
		{
			ManagementEntityTypesRegistrar.SafelyRegisterTypes(typeof(ExtendedDatabaseTraceListenerSetting));
		}

		internal static bool SaveChanges(ExtendedDatabaseTraceListenerSetting setting, ConfigurationElement sourceElement)
		{
			var element = (ExtendedDatabaseTraceListenerData)sourceElement;
			element.WriteLogSqlCommand = setting.WriteLogStoredProcName;
			element.AddCategorySqlCommand = setting.AddCategoryStoredProcName;
			element.CommandType = setting.AddCategoryStoredProcName;
			element.DatabaseInstanceName = setting.DatabaseInstanceName;
			element.Formatter = setting.Formatter;

			SourceLevels filter;
			TraceOptions traceOptions;

			if (ParseHelper.TryParseEnum(setting.Filter, out filter))
			{
				element.Filter = filter;
			}

			if (ParseHelper.TryParseEnum(setting.TraceOutputOptions, out traceOptions))
			{
				element.TraceOutputOptions = traceOptions;
			}

			return true;
		}
	}
}
